#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ctime>
#include "Protocol.hpp"

using namespace std;
using namespace protocol_ns;

void Usage(string proc)
{
    cout << "Usage: " << "+ip+port" << endl;
}
int main(int argc, char *argv[])
{
    srand(time(0));
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cerr << "socket create error" << endl;
        exit(1);
    }
    cout << "socket create success" << endl;

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = INADDR_ANY;

    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (sockfd < 0)
    {
        cerr << "connect create error" << endl;
        exit(2);
    }
    cout << "connect create success" << endl;

    while (true)
    {
        sleep(1);
        int a = rand() % 10 + 1;
        int b = rand() % 15 + 1;
        // 《送两支笔 得到一本书》

        Request req(a, b);// 两只笔
        Response resp;

        // 序列化
        string send_str;// 盒子
        req.Serialize(&send_str);// 两只笔放入盒子

        // 编码
        string Encode_str = EnCode(send_str); // 把盒子包装成快递

        // 发送
        ssize_t s = send(sockfd, Encode_str.c_str(), Encode_str.size(), 0);// 寄快递
        if (s < 0) break;

        // 接收
        char buffer[1024];
        ssize_t r = recv(sockfd, buffer, sizeof(buffer) - 1, 0);// 收快递
        if (r < 0) break;
        string recv_str;
        recv_str += buffer;

        // 解码
        string Decode_str = DeCode(recv_str);// 拆快递，取盒子
        if(Decode_str.empty()) continue;

        // 反序列化
        resp.UnSerialize(Decode_str);// 从盒子取出一本书

        cout << req._a << " + " << req._b << " = ?" << endl;
        cout << req._a << " + " << req._b << " = " << resp._result << endl;
    }

    return 0;
}